import datetime, os
from datetime import date

from wtforms.validators import NoneOf

def sizeFormat(size, is_disk=False, precision=2):
    '''
    size format for human.
        byte      ---- (B)
        kilobyte  ---- (KB)
        megabyte  ---- (MB)
        gigabyte  ---- (GB)
        terabyte  ---- (TB)
        petabyte  ---- (PB)
        exabyte   ---- (EB)
        zettabyte ---- (ZB)
        yottabyte ---- (YB)
    '''
    formats = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    unit = 1000.0 if is_disk else 1024.0
    if not(isinstance(size, float) or isinstance(size, int)):
        raise TypeError('a float number or an integer number is required!')
    if size < 0:
        raise ValueError('number must be non-negative')
    for i in formats:
        size /= unit
        if size < unit:
            return f'{round(size, precision)}{i}'
    return f'{round(size, precision)}{i}'

def delete_expire_file(days, file_path):
    print(datetime.datetime.now())
    for file in os.listdir(file_path):
        file_path_uri = os.path.join(file_path, file)

        # 第一个是文件时间、第二个是当前时间、第三个是过期时间
        filetime = datetime.datetime.fromtimestamp(os.path.getmtime(file_path_uri))
        date_now = datetime.datetime.now()
        file_expire_date = filetime + datetime.timedelta(days=days)

        # 如果是目录并且不为空，则继续递归处理
        if os.path.isdir(file_path_uri) and os.listdir(file_path_uri):
            delete_expire_file(days=days, file_path=file_path_uri)
        # 如果为空，则判断其时间是否过期，过期则删除
        # elif (not os.listdir(file_path_uri)) and (date_now > file_expire_date) and (os.path.isdir(file_path_uri)):
        elif os.path.isdir(file_path_uri) and (not os.listdir(file_path_uri)) and (date_now > file_expire_date):
            try:
                os.rmdir(file_path_uri)
                print('删除空目录：{}'.format(file_path_uri))
            except:
                print('删除空目录失败：{}'.format(file_path_uri))
            
        if (date_now > file_expire_date) and (not os.path.isdir(file_path_uri)):
            try:
                os.remove(file_path_uri)
                print('已刪除文件：{}'.format(file_path_uri))
            except:
                print('刪除文件失败：{}'.format(file_path_uri))
        else:
            print('不删除的文件：{}'.format(file_path_uri))
